#include "include.h"
#include "sgp30.h"
//scl 5
//sda 6

void PB7_out(void)
{
    // IMPLEMENT
 	GPIO_InitTypeDef  GPIO_InitStructure;
	
 	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);	 	//使能PB端口时钟
	
 	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;			
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 		 	//推挽输出
 	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 	GPIO_Init(GPIOB, &GPIO_InitStructure);				 		//初始化IO口
	
	PBout(7) = 0;
}

int main(void)
{	 
    u16 i = 0;
	
    s16 err;
    u16 tvoc_ppb, co2_eq_ppm;
    u32 iaq_baseline;
    u16 ethanol_signal, h2_signal;
	
	//延时函数初始
	delay_init();	    	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置中断优先级分组为组2：2位抢占优先级，2位响应优先级
	uart_init(115200);	 							//串口初始化为115200

	LED_Init();
	PB7_out();
	LED = 0;
	printf("Ready\r\n");
	
	delay_ms(100);
	
	PBout(7) = 1;
	
	err = sgp_probe();
	if(err != STATUS_OK)
	{
		printf("SGP sensor probing failed\r\n\r\n");
	}
	 PBout(7) = 0;
	
	//while(1);
	
//	while (sgp_probe() != STATUS_OK) {
//		 PBout(7) = 0;
//         printf("SGP sensor probing failed\r\n\r\n");
//		 delay_ms(1000);
//		PBout(7) = 1;
//    }
	LED = 1;
		printf("SGP sensor probing ok!\n");

	//PBout(7) = 1;
	
	//sgp_probe();
	
	//PBout(7) = 0;
	
	delay_ms(1000);
	
	/* Read gas signals */
	
	err = sgp_measure_signals_blocking_read(&ethanol_signal, &h2_signal);

	//
	if (err == STATUS_OK) 
	{
		printf("Ethanol signal: %d \r\n", ethanol_signal);
		printf("H2 signal: %d \r\n", h2_signal);
	} 
	else 
	{
		printf("error reading signals\n");
	}

	//
	err = sgp_iaq_init();

    while (1) {
        err = sgp_measure_iaq_blocking_read(&tvoc_ppb, &co2_eq_ppm);
        if (err == STATUS_OK)
		{
             printf("tVOC  : % 5dppb ", tvoc_ppb);
             printf("CO2eq : % 5dppm \r\n", co2_eq_ppm);
             
        } else {
             printf("error reading IAQ values\n"); 
        }

        /*
        * IMPLEMENT: get absolute humidity to enable humidity compensation
        * u32 ah = get_absolute_humidity(); // absolute humidity in mg/m^3
        * sgp_set_absolute_humidity(ah);
        */

        /* Persist the current baseline every hour */
        if (++i % 1200 == 1199) {
            err = sgp_get_iaq_baseline(&iaq_baseline);
            if (err == STATUS_OK) {
                /* IMPLEMENT: store baseline to presistent storage */
            }
        }

        /* The IAQ measurement must be triggered exactly once per second (SGP30)
         * to get accurate values.
         */
         delay_ms(1500); 
		 delay_ms(1500); 
    }
}

